package register;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import Mysql.MySQL;
import main.main;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import java.sql.PreparedStatement;

public class JoinEvent implements Listener {
	private MySQL sql;
	public JoinEvent(main plugin){
		this.plugin = plugin;
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
		MySQL sql = this.plugin.getMySQL();
		sql.queryUpdate("CREATE TABLE IF NOT EXISTS Registerd_Users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(16))");

	}
	
	
	

	
	@EventHandler
	public void onPlayerJoin(PlayerJoinEvent event){
		Player p = event.getPlayer();
			String reason = getPlayerList(p.getName());
			
			if(reason != null){
				if(p.hasPermission("proxycraft.member")){
					
				}else{
					plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(),"manpromote "+p.getName()+" Member");
					//this.getServer().dispatchCommand(this.getServer().getConsoleSender(), "manuadd "+p+" member");
                    //this.getServer().dispatchCommand(this.getServer().getConsoleSender(), "");
					p.sendMessage(ChatColor.GREEN+"Danke und viel Spass beim Spielen ;)");
				}
				
			}else {
				p.sendMessage("Bitte registrier dich auf" + ChatColor.BLUE  + " http://proxycraft.de ");
			}
		
	}

	public String getPlayerList(String Player){
		Player = Player.toLowerCase();
		MySQL sql = this.plugin.getMySQL();
		Connection conn = sql.getConnection();
		ResultSet rs = null;
		PreparedStatement st = null;
		String reason = null;
		try{
			st = conn.prepareStatement("SELECT * FROM Registerd_Users WHERE name=?");
			st.setString(1, Player);
			rs = st.executeQuery();
			rs.last();
			if(rs.getRow() != 0){
				rs.first();
				reason = rs.getString("name");
			}
		}catch (SQLException e){
			
			System.err.println("Faild to check username " + Player);
			e.printStackTrace();
		} finally {
			sql.closeResources(rs, st);
		}
		return reason;
	}
	
	/*public String setallowuser(String player){
		MySQL sql = this.plugin.getMySQL();
		if(player.length() > 16){
			player = player.substring(0, 16);
		}
		if(this.getPlayerList(player)!=null){
			System.out.println("bereitz registriert");
		}else{
		sql.queryUpdate("INSERT INTO mcuser (name) VALUES ('"+player+")'");
		System.out.println("Erfolgreich");
		}
		return player;
	}*/
	
	private main plugin;
}
